package com.haotian.aicoder.langgraph4j.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.haotian.aicoder.langgraph4j.model.enums.ImageCategoryEnum;
import com.haotian.aicoder.langgraph4j.state.ImageResource;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class UndrawIllustrationTool {

    private static final String Pixabay_Url = "https://pixabay.com/api/?key=52493415-f99ab6fd2ddd074138631c455&q=%s&image_type=photo&pretty=true";

    // https://pixabay.com/api/?key=52493415-f99ab6fd2ddd074138631c455&q=%s&image_type=photo&pretty=true
    // https://pixabay.com/api/?key=%s&q=%s&image_type=photo&pretty=true

    @Tool("搜索插画图片，用于网站美化和装饰")
    public List<ImageResource> searchIllustrations(@P("搜索关键词") String query) {
        List<ImageResource> imageList = new ArrayList<>();
        int searchCount = 12;
        String apiUrl = String.format(Pixabay_Url,query);

        // 使用 try-with-resources 自动释放 HTTP 资源
        try (HttpResponse response = HttpRequest.get(apiUrl).timeout(10000).execute()) {
            if (!response.isOk()) {
                log.warn("HTTP请求失败，状态码: {}", response.getStatus());
                return imageList;
            }

            JSONObject result = JSONUtil.parseObj(response.body());

            // Pixabay API使用"hits"字段而不是"pageProps.initialResults"
            JSONArray hits = result.getJSONArray("hits");
            if (hits == null || hits.isEmpty()) {
                log.warn("搜索结果为空");
                return imageList;
            }

            int actualCount = Math.min(searchCount, hits.size());
            for (int i = 0; i < actualCount; i++) {
                JSONObject hit = hits.getJSONObject(i);
                String tags = hit.getStr("tags", "插画");
                // 使用Pixabay的图片URL字段
                String imageUrl = hit.getStr("webformatURL", "");
                if (StrUtil.isNotBlank(imageUrl)) {
                    imageList.add(ImageResource.builder()
                            .category(ImageCategoryEnum.ILLUSTRATION)
                            .description(tags)
                            .url(imageUrl)
                            .build());
                }
            }
        } catch (Exception e) {
            log.error("搜索插画失败：{}", e.getMessage(), e);
        }
        return imageList;
    }

}
